package com.Travit;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.*;
import android.util.*;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;



public class RecieveShipment extends Activity{

	private static TextView vendorID;
	private static TextView vendorName;
	private static TextView sourceAddress;
	private static TextView destinationAddress;
	private static TextView productName;
	private static TextView productType;
	private static TextView scannedcode;
	
	private static Button cancelShipmentButton;
	private static Button recieveShipmentButton;
	private static ImageButton logoutButton;
	private static ImageButton goToHomePageButton;
	
	private static TextView updatedBy;
	private static TextView distributorAddress;
	
	
	private static Button next1;
	private static Button next2;
	List<NameValuePair> pairs;
	
	private static String urlRequestValidateBoxBarcode = "http://project492.engr.sjsu.edu/travITvalidateProduct.php";
	private static String urlRequestUser = "http://project492.engr.sjsu.edu/travITaccountsDetails.php";
	private static String urlRequestSearchProducts = "http://project492.engr.sjsu.edu/travITsearchProduct.php";
	private static String urlRequest = "http://project492.engr.sjsu.edu/travIT.php";
	private static String urlRequestSearchStores = "http://project492.engr.sjsu.edu/travITsearchStores.php";
	private static String urlRequestValidateRecieveShipment = "http://project492.engr.sjsu.edu/travITvalidateProduct.php";
	private static String urlRequestForHistory = "http://project492.engr.sjsu.edu/travITgetScanDetails.php";
	private static String boxBarCodeID="";
	private static String status="";
	private static String updatedByType="";
	private static String loggedid="";
	private static String loggedname="";
	private static String string1="";
	private static String string2="";
	private static String scannedbrcode="";
	String dateUpdated="";
	String getnamecategory="";
	//private static String[] responseResultArr;
	
	public void onCreate(Bundle savedInstanceState){
		
		super.onCreate(savedInstanceState);
		Bundle extras = getIntent().getExtras();
		loggedid = extras.getString("loggedid");
		loggedname = extras.getString("loginname");
		boxBarCodeID=extras.getString("BoxBarCodeID");
		status=extras.getString("status");
		scannedbrcode=extras.getString("scannedbarcode");
		
		final String[] responseResultArr= (String[]) extras.get("Table");
		Log.v("RArr:",""+responseResultArr);
		Hashtable<String,String>table=new Hashtable<String,String>();
		for(int i=0;i<responseResultArr.length;i+=2){
			Log.v("response:",responseResultArr[i]);
			int tempVar=i;
			tempVar++;
			Log.v("result:",responseResultArr[tempVar]);
			table.put(responseResultArr[i],responseResultArr[tempVar]);
		}
		
		Log.v("Recieving","RecieveShipment");
		setContentView(R.layout.receiving);
		updatedByType=extras.getString("updatedByType");
		Log.v("Recieving","Is Fine");
		
		vendorID=(TextView) findViewById(R.id.vendorIDText);
		vendorName=(TextView) findViewById(R.id.vendorNameText);
		productName=(TextView)findViewById(R.id.productNameText);
		productType=(TextView)findViewById(R.id.productTypeText);
		scannedcode=(TextView)findViewById(R.id.scannedcode);
		scannedcode.setText(scannedbrcode);
		
		TextView topname = (TextView) findViewById(R.id.distributorlogintext);
		topname.setText("Welcome " + loggedname + "!");
		
		Log.v("In Shipement","Recieving");
		Log.v("Recieved Table",""+table);
		
		String tempAddress=table.get("Source");
		tempAddress.replace(",","\n");
		table.put("Source", tempAddress);
		tempAddress=table.get("Destination");
		tempAddress.replace(",","\n");
		table.put("Destination", tempAddress);
		
//		sourceAddress.setText(table.get("Source"));
//		destinationAddress.setText(table.get("Destination"));
		final String sourceadd = table.get("Source");
		final String destadd = table.get("Destination");
		productName.setText(table.get("Product Name"));
		productType.setText(table.get("Product Category"));
		vendorID.setText(table.get("VendorID"));
		
		goToHomePageButton = (ImageButton) findViewById(R.id.homepage);
		goToHomePageButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(updatedByType.equalsIgnoreCase("Distributor")){
					Log.v("updated","updated");
					Intent disIntent = new Intent(v.getContext(), Distributor.class);
					disIntent.putExtra("loginname", vendorName.getText().toString());
					disIntent.putExtra("shipped", "status");
					disIntent.putExtra("loggedid", loggedid);
					startActivity(disIntent);
					}else{
						Log.v("updated","updated");
						Intent disIntent = new Intent(v.getContext(), Retail.class);
						disIntent.putExtra("shipped", "status");
						disIntent.putExtra("loggedinuser", vendorName.getText().toString());
						disIntent.putExtra("loggedid", loggedid);
						startActivity(disIntent);
					}
			}
		});
		
	      
        HttpGet request = new HttpGet(urlRequestUser
				+ "?usernameID="+Integer.parseInt(table.get("VendorID")));
		HttpClient client = new DefaultHttpClient();
		Log.v("Request;",request.toString());
		try{
			HttpResponse response=client.execute(request);
			HttpEntity entity = response.getEntity();
			Log.v("entity:",entity.toString());
			String responseResult = EntityUtils.toString(entity);
			Hashtable<String,String> usertable=new Hashtable<String, String>();
			String[] responseArr=responseResult.split(";");
			responseArr[0]=responseArr[0].trim();
			for(int i=0;i<responseArr.length;i+=2){
				int temp=i;
				temp++;
				Log.v("error:;","usertable");
				Log.v(responseArr[i], responseArr[temp]);
				usertable.put(responseArr[i], responseArr[temp]);
			}
			
			if(usertable.get("Status").equals("Unknown Vendor")){
				vendorName.setText("Vendor ID is not VALID");
			}else{
				vendorName.setText(usertable.get("Value"));
				
			   //goToHomePageButton.setOnClickListener(new click());
			   //cancelShipmentButton.setOnClickListener(new clicker());
			}
			Log.v("Box Results::",responseResult);
			
			Log.v("hahahahhahaha","hahahahhaha");
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			logoutButton = (ImageButton) findViewById(R.id.logout);
			logoutButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Log.v("starting", "recieving final");
					//disView=v;
					Intent newIntent = new Intent(v.getContext(), TravITActivity.class);
					//newIntent.putExtra("venid", loggedid);
					startActivity(newIntent);
				}			
			});

			next1 = (Button) findViewById(R.id.nextbutton1);
			next1.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					
					setContentView(R.layout.receivingnext);
					setTitle(R.string.distnext);
					TextView topname = (TextView) findViewById(R.id.distributorlogintext);
					topname.setText("Welcome " + loggedname + "!");
					Log.v("should", "change view");
					logoutButton = (ImageButton) findViewById(R.id.logout);
					logoutButton.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							Log.v("starting", "recieving final");
							//disView=v;
							Intent newIntent = new Intent(v.getContext(), TravITActivity.class);
							//newIntent.putExtra("venid", loggedid);
							startActivity(newIntent);
						}			
					});

					goToHomePageButton = (ImageButton) findViewById(R.id.homepage);
					goToHomePageButton.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if(updatedByType.equalsIgnoreCase("Distributor")){
								Log.v("updated","updated");
								Intent disIntent = new Intent(v.getContext(), Distributor.class);
								disIntent.putExtra("loginname", vendorName.getText().toString());
								disIntent.putExtra("shipped", "status");
								disIntent.putExtra("loggedid", loggedid);
								startActivity(disIntent);
								}else{
									Log.v("updated","updated");
									Intent disIntent = new Intent(v.getContext(), Retail.class);
									disIntent.putExtra("shipped", "status");
									disIntent.putExtra("loggedinuser", vendorName.getText().toString());
									disIntent.putExtra("loggedid", loggedid);
									startActivity(disIntent);
								}
						}
					});
					
					sourceAddress=(TextView)findViewById(R.id.sourceAddress);
					destinationAddress=(TextView)findViewById(R.id.destinationAddress);
					sourceAddress.setText(sourceadd);
					destinationAddress.setText(destadd);
					
					cancelShipmentButton=(Button)findViewById(R.id.cancelShipmentButton);
					cancelShipmentButton.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if(updatedByType.equalsIgnoreCase("Distributor")){
							Log.v("updated","updated");
							Intent disIntent = new Intent(v.getContext(), Distributor.class);
							disIntent.putExtra("loginname", vendorName.getText().toString());
							disIntent.putExtra("shipped", "status");
							disIntent.putExtra("loggedid", loggedid);
							startActivity(disIntent);
							}else{
								Log.v("updated","updated");
								Intent disIntent = new Intent(v.getContext(), Retail.class);
								disIntent.putExtra("shipped", "status");
								disIntent.putExtra("loggedinuser", vendorName.getText().toString());
								disIntent.putExtra("loggedid", loggedid);
								startActivity(disIntent);
							}
						}
					});
					updatedBy=(TextView)findViewById(R.id.receivedByEmployeeName);
					distributorAddress=(TextView)findViewById(R.id.currentDistributorAddress);

					next2 = (Button) findViewById(R.id.finalnext);
					
					next2.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if(!updatedBy.getText().toString().equals("") && !distributorAddress.getText().toString().equals(""))
							{
								setContentView(R.layout.receivingdatetime);
								setTitle(R.string.distnext);
							TextView topname = (TextView) findViewById(R.id.distributorlogintext);
							topname.setText("Welcome " + loggedname + "!");
							logoutButton = (ImageButton) findViewById(R.id.logout);
							logoutButton.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									Log.v("starting", "recieving final");
									//disView=v;
									Intent newIntent = new Intent(v.getContext(), TravITActivity.class);
									//newIntent.putExtra("venid", loggedid);
									startActivity(newIntent);
								}			
							});

							goToHomePageButton = (ImageButton) findViewById(R.id.homepage);
							goToHomePageButton.setOnClickListener(new OnClickListener() {
								
								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									if(updatedByType.equalsIgnoreCase("Distributor")){
										Log.v("updated","updated");
										Intent disIntent = new Intent(v.getContext(), Distributor.class);
										disIntent.putExtra("loginname", vendorName.getText().toString());
										disIntent.putExtra("shipped", "status");
										disIntent.putExtra("loggedid", loggedid);
										startActivity(disIntent);
										}else{
											Log.v("updated","updated");
											Intent disIntent = new Intent(v.getContext(), Retail.class);
											disIntent.putExtra("shipped", "status");
											disIntent.putExtra("loggedinuser", vendorName.getText().toString());
											disIntent.putExtra("loggedid", loggedid);
											startActivity(disIntent);
										}
								}
							});

							cancelShipmentButton=(Button)findViewById(R.id.cancelShipmentButton);
							cancelShipmentButton.setOnClickListener(new OnClickListener() {
								
								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									if(updatedByType.equalsIgnoreCase("Distributor")){
									Log.v("updated","updated");
									Intent disIntent = new Intent(v.getContext(), Distributor.class);
									disIntent.putExtra("loginname", vendorName.getText().toString());
									disIntent.putExtra("loggedid", loggedid);
									disIntent.putExtra("shipped", "status");
									startActivity(disIntent);
									}else{
										Log.v("updated","updated");
										Intent disIntent = new Intent(v.getContext(), Retail.class);
										disIntent.putExtra("loggedinuser", vendorName.getText().toString());
										disIntent.putExtra("shipped", "status");
										disIntent.putExtra("loggedid", loggedid);
										startActivity(disIntent);
									}
									
								}
							});
							recieveShipmentButton=(Button)findViewById(R.id.recieveShippmentButton);
						    //logoutButton=(Button)findViewById(R.id.logout);
						    //goToHomePageButton=(Button)findViewById(R.id.homepage);
						    //logoutButton.setOnClickListener(new clicker());
						   recieveShipmentButton.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								Log.v("here","here");
								TimePicker time=(TimePicker)findViewById(R.id.recievedShipmentTime);
								Log.v("time to string:",""+time.toString());
								Log.v("get current hour:",""+time.getCurrentHour());
								Log.v("get current minute:",""+time.getCurrentMinute());
								
								DatePicker date=(DatePicker)findViewById(R.id.recievedShipmentDate);
								Log.v("Date to string :",""+date.toString());
								Log.v("Date day of month:",""+date.getDayOfMonth());
								Log.v("Date og month:",""+date.getMonth());
								Log.v("Date of year:",""+date.getYear());
								
								dateUpdated=date.getYear()+"-"+date.getMonth()+"-"+date.getDayOfMonth()+" "+time.getCurrentHour()+":"+time.getCurrentMinute()+":00";
								HttpClient client = new DefaultHttpClient();
								try {
									HttpPost request = new HttpPost(urlRequestValidateRecieveShipment);
//									List<NameValuePair> pairs = new ArrayList<NameValuePair>();
									pairs = new ArrayList<NameValuePair>();
									pairs.add(new BasicNameValuePair("dateRecieved",
											dateUpdated));
									pairs.add(new BasicNameValuePair("status",
										status));
									pairs.add(new BasicNameValuePair("sourceAddress",
											sourceAddress.getText().toString()));
									pairs.add(new BasicNameValuePair("destinationAddress",
											destinationAddress.getText().toString()));
									pairs.add(new BasicNameValuePair("distributorAddress",
											distributorAddress.getText().toString()));
									pairs.add(new BasicNameValuePair("updatedBy",
											updatedBy.getText().toString()));
									pairs.add(new BasicNameValuePair("boxBarCodeID",
											boxBarCodeID));
									pairs.add(new BasicNameValuePair("productName",
											productName.getText().toString()));
									pairs.add(new BasicNameValuePair("updatedByType",
											updatedByType));
									
									request.setEntity(new UrlEncodedFormEntity(
											pairs));
									HttpResponse response = client.execute(request);
									HttpEntity entity = response.getEntity();
									String res = EntityUtils.toString(entity).trim();
									Log.v("REAREAREAREA",res);
									
									if(res.equals("Updated")){		
										//ADD HISTORY PART
							            HttpGet requestproduct = new HttpGet(urlRequestForHistory
							    				+ "?barcodeID="+boxBarCodeID);
							    		HttpClient client1 = new DefaultHttpClient();
							    		Hashtable<String,String> table;
							    		
							    		try{
							    			HttpResponse response1=client.execute(requestproduct);
							    			HttpEntity entity1 = response1.getEntity();
							    			Log.v("entity:",entity1.toString());
							    			String responseResult = EntityUtils.toString(entity1);
							    			Log.v("Box Results::",responseResult);
							    			
							    			Log.v("hahahahhahaha","hahahahhaha");
							    			String[] responseResultArr=responseResult.split(";");
							    			table=new Hashtable<String,String>();
							    			for(int i=0;i<responseResultArr.length;i+=2)
							    			{
							    				Log.v(""+i, ""+responseResultArr[i]);
							    				//CHANGED - table commented
//							    				Log.v("response:",responseResultArr[i]);
//							    				int tempVar=i;
//							    				tempVar++;
//							    				Log.v("result:",responseResultArr[tempVar]);
//							    				table.put(responseResultArr[i],responseResultArr[tempVar]);
							    			}
							    			string1 = responseResultArr[1];
							    			string2 = responseResultArr[3];
							    		} catch(Exception e) {
							    			// TODO Auto-generated catch block
							    			e.printStackTrace();
							    		}
							    		
							    		//1 and 3
										HttpClient client2 = new DefaultHttpClient();
										try {
											Log.v("should", "update with" + loggedid);
											HttpPost request2 = new HttpPost(urlRequestForHistory);
//											List<NameValuePair> pairs = new ArrayList<NameValuePair>();
											pairs = new ArrayList<NameValuePair>();
											pairs.add(new BasicNameValuePair("scanningID",
													loggedid));
											pairs.add(new BasicNameValuePair("scanningName",
													loggedname));
											pairs.add(new BasicNameValuePair("scanningType",
													status));
											pairs.add(new BasicNameValuePair("scannedID",
													boxBarCodeID));
											pairs.add(new BasicNameValuePair("name",
													string2));
											pairs.add(new BasicNameValuePair("category",
													string1));
											request2.setEntity(new UrlEncodedFormEntity(
													pairs));
											HttpResponse response2 = client2.execute(request2);
											HttpEntity entity2 = response2.getEntity();
											String res2 = EntityUtils.toString(entity2).trim();
										}catch(Exception e){
											
										}
										
										Log.v("updated","updated");
										AlertDialog.Builder altDialog= new AlertDialog.Builder(RecieveShipment.this);
										altDialog.setMessage("Successfully Updated!"); // here add your message
										altDialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
										   
										   @Override
										   public void onClick(DialogInterface dialog, int which) {
										    // TODO Auto-generated method stub
											   dialog.cancel();
										   }
										  });
										altDialog.show();
										if(updatedByType.equalsIgnoreCase("Distributor")){
										Intent disIntent = new Intent(v.getContext(), Distributor.class);
										disIntent.putExtra("loginname", loggedname);
										disIntent.putExtra("loggedid", loggedid);
										disIntent.putExtra("shipped", "status");
										startActivity(disIntent);
										}else{
											Intent disIntent = new Intent(v.getContext(), Retail.class);
											disIntent.putExtra("recieved", "status");
											disIntent.putExtra("loggedinuser", loggedname);
											disIntent.putExtra("loggedid", loggedid);
											disIntent.putExtra("loginname", loggedname);
											startActivity(disIntent);
												
										}
									}else{
										Log.v("Error","Error");
									}
								}catch(Exception e){
									
								}
							}
						});
							}//END IF
							else
							{
								updatedBy.setHint("Please enter your name");
								distributorAddress.setHint("Please enter your address");
//								AlertDialog.Builder builder = new AlertDialog.Builder(RecieveShipment.this);
//								builder.setMessage("Please enter both fields.")
//								       .setCancelable(true)
//								       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//								           public void onClick(DialogInterface dialog, int id) {
//								                RecieveShipment.this.finish();
//								           }
//								       });
//								       
//								AlertDialog alert = builder.create();
							}
						}
							
					});
				
				}
			});
			

	}
	
	public class click implements Button.OnClickListener {
	
		
		@Override
		public void onClick(View v) {
			Log.v("clicked",v.toString());
			
			// TODO Auto-generated method stub
			System.out.println("Here:" + v.toString());
			if(v==logoutButton){
				
			}else if(v==cancelShipmentButton){
				
			}else if (v==goToHomePageButton){
				
			}else if(v==recieveShipmentButton){
				String vendorID=findViewById(R.id.vendorIDText).toString();
				String vendorName=findViewById(R.id.vendorNameText).toString();
				String productType=findViewById(R.id.productTypeText).toString();
				String productName=findViewById(R.id.productNameText).toString();
				String recievedBy=findViewById(R.id.receivedByEmployeeName).toString();
				String distributorAddress=findViewById(R.id.currentDistributorAddress).toString();
				String sourceAddress=findViewById(R.id.sourceAddress).toString();
				String destinationAddress=findViewById(R.id.destinationAddress).toString();
				TimePicker time=(TimePicker)findViewById(R.id.recievedShipmentTime);
				Log.v("time to string:",""+time.toString());
				Log.v("get current hour:",""+time.getCurrentHour());
				Log.v("get current minute:",""+time.getCurrentMinute());
				DatePicker date=(DatePicker)findViewById(R.id.recievedShipmentDate);
				Log.v("Date to string :",""+date.toString());
				Log.v("Date day of month:",""+date.getDayOfMonth());
				Log.v("Date og month:",""+date.getMonth());
				Log.v("Date of year:",""+date.getYear());
			}
		}
	}
	
	
	public void usedabove(){
		
	}
	
}




